<?php
/**
 * Created by PhpStorm.
 * User: 图图
 * Date: 2021-6-8
 * Time: 16:29
 */

namespace app\api\controller;

use app\common\controller\Api;
use app\common\model\Duanwei;
use app\common\model\Factor;
use app\common\model\Fenorder;
use app\common\model\HandCard;
use app\common\model\Orderproject;
use app\common\service\OrdinaryService;
use app\common\service\ReceiverService;
use app\common\service\VoiceService;
use Carbon\Carbon;
use think\Db;
use think\Exception;
use app\common\model\HandCard as HandCardM;
use app\common\model\Order;

/**
 * 技师控制器
 * @package app\index\controller
 */
class Engineer extends Auth
{
    public $noNeedLogin = [];

    /**
     * 获取全部技师
     */
    public function index(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $where = [];
            //技师性别筛选
            if(!empty($getData['sex'])){
                $where['u.sex'] = $getData['sex'];
            }
            //技师项目筛选
            if(!empty($getData['top_type_id'])){
                $where['u.top_type_id'] = $getData['top_type_id'];
            }
            //技师工作状态筛选
            if(!empty($getData['work_status'])){
                $where['u.work_status'] = $getData['work_status'];
            }
            //工号筛选
            if(!empty($getData['work_number'])){
                $where['u.work_number'] = $getData['work_number'];
            }
            //班次筛选
            if(!empty($getData['work_type'])){
                $where['u.work_type'] = $getData['work_type'];
            }
            //其他筛选条件
            $where['u.store_id'] = $this->userInfo['store_id'];
            $where['u.role'] = '3';
            $sql = Db::name('qt_order_queue')
                ->field('oq.id,u.id as user_id,u.work_number,u.sex,wt.title as name,oq.room_id,oq.sort,u.work_type,u.work_status,st.title as work_title,oq.head,oq.foot,oq.start_time,oq.end_time,u.top_type_id')
                ->alias('oq')
                ->leftJoin('qt_users u','u.id = oq.user_id')
                ->leftJoin('qt_work_type wt','wt.id = u.top_type_id')
                ->leftJoin('qt_scheduling_type st','st.id = u.work_type')
                ->where($where)
                ->where(['u.role'=>'3','u.status'=>'0']);
            //项目筛选
            if(!empty($getData['project_id'])){
                $sql->leftJoin('qt_user_project up','up.engineer_id =  u.id')
                    ->where('up.project_id',$getData['project_id']);
            }
            if(!isset($getData['sort_type'])){
                $getData['sort_type'] = '0';
            }
            if($getData['sort_type'] == '1'){
                //工号排序
                $order = 'u.work_number asc';
            }elseif ($getData['sort_type'] == '2'){
                //下钟时间
                $order = 'oq.real_time desc';
            }else{
                //默认钟房顺序
                $order = 'oq.sort  asc';
            }
            //总数据
            $originalData = $sql->order($order)->select();
            foreach ($originalData as $key=>$value){
                $originalData[$key]['clock'] = Db::name('qt_commission_log')
                    ->where(['user_id'=>$value['user_id'],'type'=>'1','status'=>'2'])
                    ->whereTime('created_time','today')
                    ->count();
                $originalData[$key]['row'] = Db::name('qt_commission_log')
                    ->where(['user_id'=>$value['user_id'],'type'=>'1','status'=>'1'])
                    ->whereTime('created_time','today')
                    ->count();
                $room = Db::name('qt_room')
                    ->field('r.*,s.name as type_name,s.color as room_color')
                    ->alias('r')
                    ->leftJoin('qt_room_status s ','s.id = r.status_id')
                    ->where(['r.id'=>$value['room_id']])
                    ->find();
                $project = Db::name('qt_order_project')
                    ->field('op.*,p.id as project,p.name as project_name,p.time')
                    ->alias('op')
                    ->leftJoin('qt_project p','op.project_id = p.id')
                    ->where(['op.room_id'=>$value['room_id'],'op.engineer_id'=>$value['user_id']])
                    ->where('op.is_delete',2)
                    ->order('id desc')
                    ->find();
                $originalData[$key]['room'] = $room['name'];
                $originalData[$key]['color'] = '';
                $originalData[$key]['room_color'] = Db::name('qt_work_status_color')->where('id',$value['work_status'])->value('color');
                if($value['work_status'] == '6'){
                    $originalData[$key]['room_color'] = 'rgb(148,173,50)';
                }
                if($value['work_status'] == '7'){
                    $originalData[$key]['room_color'] = 'rgb(254,152,0)';
                }
                $originalData[$key]['project_id'] = $project['id'];//项目订单ID
                $originalData[$key]['time'] = $project['time'];
                $originalData[$key]['project_type'] = $project['order_type'];
                $originalData[$key]['project_status'] = $project['status'];
                $originalData[$key]['project'] = $project['project'];//项目ID
                $originalData[$key]['project_name'] = $project['project_name'];//项目名称
                $originalData[$key]['key'] = $key;//键值对
                $originalData[$key]['add'] = 0;//加钟数量
                //技师是否有预约
                $appointment = Db::name('qt_room_appointment')->where(['engineer_id'=>$value['user_id'],'status'=>'1'])->find();
                if(empty($appointment)){
                    $originalData[$key]['appointment'] = 0;//没有预约
                }else{
                    $originalData[$key]['appointment'] = 1;//有预约
                    if($value['work_status'] == '1'){
                        $originalData[$key]['room_color'] = Db::name('qt_work_status_color')->where('id','3')->value('color');
                    }
                }
                if(!empty($project) && $project['order_type'] == '2'){
                    $originalData[$key]['room_color'] = 'rgb(210,50,45)';
                }
                if(!empty($project) && $project['order_type'] == '3'){
                    $originalData[$key]['room_color'] = 'rgb(210,50,45)';
                }
            }
            $this->result('查询成功', $originalData, 200);
        }
    }

    /**
     * 技师圈牌
     */
    public function circleCard(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少技师', '', 204);
            }
            $update = Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'6']);
            if($update !== false){
                $this->result('设置成功', '', 200);
            }
            $this->result('设置失败', '', 204);
        }
    }

    /**
     * 技师圈牌
     */
    public function delCircleCard(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少技师', '', 204);
            }
            $update = Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'1']);
            if($update !== false){
                $this->result('设置成功', '', 200);
            }
            $this->result('设置失败', '', 204);
        }
    }

    /**
     * 获取所有技师
     */
    public function lists(){
        if ($this->request->isPost()) {
            $data = Db::name('qt_users')
                ->field('id,work_number,work_status,sex')
                ->where(['store_id' => $this->userInfo['store_id'], 'group' => '1','status'=>'0'])
                ->select();
            $this->result('查询成功', $data, 200);
        }
    }

    /**
     * 获取未排班技师列表
     * @throws Exception
     * @throws \think\db\exception\DbException
     * @throws \think\exception\PDOException
     */
    public function noScheduling()
    {
        if ($this->request->isPost()) {
            $data = Db::name('qt_users')
                ->field('id,real_name,work_number')
                ->where(['store_id'=>$this->userInfo['store_id'],'role'=>'3','status'=>'0','work_type'=>'0'])
                ->select();
            $this->result('查询成功', $data, 200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 添加技师排班
     */
    public function engineerScheduling(){
        if ($this->request->isPost()) {
            $userInfo = $this->userInfo;
            $getData = $this->request->post();
            if(!isset($getData['scheduling_id']) || empty($getData['scheduling_id'])){
                $this->result('缺少参数', '', 204);
            }
            if(!isset($getData['engineer_id']) || empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $engineerRes = [];
            $engineerIds = explode(',',$getData['engineer_id']);
            $sortRes = Db::name('qt_scheduling_queue')
                ->where(['store_id'=>$userInfo['store_id'],'type_id'=>$getData['scheduling_id']])
                ->order('sort desc')
                ->limit('1')
                ->find();
            if(empty($sortRes)){
                $sort = 1;
            }else{
                $sort = $sortRes['sort'] + 1;
            }
            foreach ($engineerIds as $key=>$value){
                $engineerRes[$key]['store_id'] = $userInfo['store_id'];
                $engineerRes[$key]['engineer_id'] = $value;
                $engineerRes[$key]['sort'] = $sort;
                $engineerRes[$key]['type_id'] = $getData['scheduling_id'];
                $engineerRes[$key]['created_time'] = time();
                $sort ++ ;
            }
            $insert = Db::name('qt_scheduling_queue')->insertAll($engineerRes);

            //更新技师排班ID
            Db::name('qt_users')->whereIn('id',$engineerIds)->update(['work_type'=>$getData['scheduling_id']]);

            if($insert){
                $this->result('添加成功', '', 200);
            }
            $this->result('添加失败，请稍后再试', '', 204);
        }
        $this->result('无效的请求', '', 204);
    }



    /**
     * 上钟
     */
    public function  start_project(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['order_id']) || empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            if($this->storeInfo['type'] != '1'){
                if(!isset($getData['hand_card_name']) || empty($getData['hand_card_name'])){
                    $this->result('请填写手牌号', '', 204);
                }
            }
            //处理手牌号
            if(isset($getData['hand_card_name']) && !empty($getData['hand_card_name'])){
                $handCardData = Db::name('qt_hand_card')
                    ->where(['store_id'=>$this->userInfo['store_id'],'name'=>$getData['hand_card_name']])
                    ->find();
                if(empty($handCardData)){
                    $this->result('无效的手牌', '', 204);
                }
                if($handCardData['status'] != '2'){
                    $this->result('手牌未发放', '', 204);
                }
                Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->update(['hand_card_id'=>$handCardData['id']]);
                //检测停牌
                $checkStatus = HandCard::checkStatus($handCardData['id']);
                if($checkStatus == false){
                    $this->result('手牌状态有问题', '', 204);
                }
                //检测最大消费金额
                $money = Db::name('qt_order_project')->where('is_delete',2)->where(['id'=>$getData['order_id']])->value('price');
                $checkMoney = HandCard::checkMaxMoney($handCardData['id'],$money);
                if($checkMoney == false){
                    $this->result('超出手牌最大消费金额', '', 204);
                }
                //查询总金额
                $money = Db::name('qt_order_project')->where('is_delete',2)->where(['id'=>$getData['order_id']])->value('price');
                //给手牌加金额
                Db::name('qt_hand_grant')
                    ->where(['hand_card_id'=>$handCardData['id']])
                    ->where(['status'=>'2'])
                    ->setInc('money',$money);
            }
            //判断提成模式
            $orderProjectData = Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->find();
            if($this->storeInfo['receiver_order_commission_type'] == '3'){
                if($orderProjectData['old_name'] != null || $orderProjectData['old_name'] != ''){
                    //更新提成记录
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$getData['order_id']])->update(['receiver'=>0]);
                    //更新订单提成
                    Db::name('qt_order_project')->where(['id'=>$getData['order_id']])->update(['receiver'=>0]);
                }
            }
            $OrderprojectModel = new Orderproject();
            $res=$OrderprojectModel->start_project($getData['order_id'],$getData['engineer_id'],'1',$this->userInfo);
            if($res['status']){
                //上钟成功播报
                $voiceResult = VoiceService::createVoice('上钟成功');
                if($voiceResult['code'] == 0){
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'],'上钟成功',$voiceResult['data'],'5','3',$getData['engineer_id']);
                }
                $this->result('上钟成功', '', 200);
            }else{
                $this->result('上钟失败', $res['msg'], 204);
            }
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     *下钟操作
     */
    public function end_project(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['order_id']) || empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            //查询当前技师的其他的项目
            $orderProject = Db::name('qt_order_project')->where(['id' => $getData['order_id']])->find();
            $OrderprojectModel = new Orderproject();
            $res = $OrderprojectModel->start_project($orderProject['id'], $orderProject['engineer_id'], '2', $this->userInfo);
            //判断房间是否还有未支付的项目订单
            $noPayOrderProject = Db::name('qt_order_project')->where('is_delete',2)->where(['room_id'=>$orderProject['room_id'],'pay_status'=>'0'])->find();
            if($noPayOrderProject == null){
                Db::name('qt_order')->where(['id'=>$orderProject['order_id']])->update(['pay_status'=>'2']);
            }
            if($res['status']){
                //下钟成功播报
                $voiceResult = VoiceService::createVoice('下钟成功');
                if($voiceResult['code'] == 0){
                    VoiceService::saveVoiceMsg($this->userInfo['store_id'],'下钟成功',$voiceResult['data'],'6','3',$getData['engineer_id']);
                }
                //下钟动排
                $storeRule = Db::name('qt_queue_rule')->where(['type' => '1', 'store_id' => $this->userInfo['store_id']])->find();
                if($storeRule['is_down_act'] == '1'){
                    $endSort = Db::name('qt_order_queue')
                        ->where(['store_id' => $this->userInfo['store_id']])
                        ->order('sort desc')
                        ->find();
                    Db::name('qt_order_queue')->where(['store_id'=>$this->userInfo['store_id'],'user_id'=>$getData['engineer_id']])->update(['sort'=>$endSort['sort'] + 1]);
                }
                //判断是否有多钟排位
                $manyQueueData = Db::name('qt_order_many_queue')
                    ->field('queue.*,rule.is_down_act')
                    ->alias('queue')
                    ->leftJoin('qt_many_queue_rule rule','rule.id = queue.many_queue_id')
                    ->where([
                        'queue.store_id'=>$this->userInfo['store_id'],
                        'queue.user_id'=>$getData['engineer_id'],
                        'queue.project_id'=>$orderProject['project_id']
                    ])->find();
                if($manyQueueData['is_down_act'] == '1'){
                    $endSort = Db::name('qt_order_many_queue')
                        ->where(['many_queue_id' => $manyQueueData['many_queue_id']])
                        ->max('sort');
                    Db::name('qt_order_many_queue')->where(['id'=>$manyQueueData['id'],])->update(['sort'=>$endSort + 1]);
                }
                $this->result('下钟成功', '', 200);
            }else{
                $this->result('下钟失败', $res['msg'], 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 获取技师详情
     */
    public function detail(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $orderQueue = Db::name('qt_order_queue')
                ->where('user_id',$getData['engineer_id'])
                ->find();
            $data = Db::name('qt_order_project')
                ->alias('op')
                ->field('op.id,r.name as room_name,op.name as project_name,op.start_time,op.end_time,op.real_end_time,op.order_type,op.project_id')
                ->leftJoin('qt_room r','r.id = op.room_id')
                ->where(['op.engineer_id'=>$getData['engineer_id'],'op.room_id'=>$orderQueue['room_id'],'is_change'=>'1'])
                ->where('op.is_delete',2)
                ->whereIn('op.status',['1','2','3'])
                ->select();
            $this->result('查询成功', $data, 200);
        }else{
            $this->result('无效的请求', '', 204);
        }
    }

    /**
     * 技师上班
     */
    public function go_work(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $update = Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'1']);
            $find = Db::name('qt_order_queue')
                ->where('store_id',$this->userInfo['store_id'])
                ->where('user_id',$getData['engineer_id'])
                ->order('sort desc')
                ->find();
            //如果没有在排位里面先添加
            if(empty($find)){
                $queue = Db::name('qt_order_queue')->where('store_id')->order('sort desc')->find();
                $sort = $queue['sort'] + 1;
                $insert = [
                    'store_id'=>$this->userInfo['store_id'],
                    'user_id'=>$getData['engineer_id'],
                    'sort'=>$sort,
                    'day'=>date('Y-m-d'),
                    'type_id'=>date('Y-m-d'),
                    'created_time'=>time(),
                    'status'=>'1',
                ];
                Db::name('qt_order_queue')->insert($insert);
            }
            //增加打卡记录
            $week = Carbon::now()->dayOfWeekIso;//星期
            $insertData['user_id'] = $getData['engineer_id'];
            $insertData['other_user_id'] = $this->userInfo['id'];
            $insertData['store_id'] = $this->userInfo['store_id'];
            $insertData['week'] =$week;
            $insertData['day'] =strtotime(date('Y-m-d')) ;
            $insertData['work_type'] ='1';
            $insertData['created_time'] = time();
            $insertData['type'] = '1';
            Db::name('qt_work_log')->insert($insertData);
            //处理技师排钟
            $storeRule = storeQueue($this->userInfo['store_id']);
            if($storeRule['rule'] == '3'){
                //将该技师置头牌
                topSort($this->userInfo['store_id'],$getData['engineer_id']);
            }
            if($update !== false){
                $this->result('上班成功', '', 200);
            }else{
                $this->result('上班失败', '', 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 技师下班
     */
    public function off_work(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id'])){
                $this->result('缺少参数', '', 204);
            }
            $workStatus = Db::name('qt_users')->where('id',$getData['engineer_id'])->value('work_status');
            if($workStatus != '1'){
                $this->result('该技师暂时不支持下班', '', 204);
            }
            $update = Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'2']);
            //增加打开记录
            $week = Carbon::now()->dayOfWeekIso;//星期
            $insertData['user_id'] = $getData['engineer_id'];
            $insertData['other_user_id'] = $this->userInfo['id'];
            $insertData['store_id'] = $this->userInfo['store_id'];
            $insertData['week'] =$week;
            $insertData['day'] =strtotime(date('Y-m-d')) ;
            $insertData['work_type'] ='2';
            $insertData['created_time'] = time();
            $insertData['type'] = '1';
            Db::name('qt_work_log')->insert($insertData);
            if($update !== false){
                $this->result('下班成功', '', 200);
            }else{
                $this->result('下班失败', '', 204);
            }

        } else {
            $this->result('非法请求', '', 204);
        }
    }

    /**
     * 添加考勤登记
     */
    public function attendance_add(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            $validate = new \app\web\validate\Attendance();
            if (!$validate->scene('add')->check($getData)) {
                $this->result($validate->getError(), '', 204);
            }
            $getData['start_time'] = strtotime($getData['start_time']);
            $getData['end_time'] = strtotime($getData['end_time']);
            $getData['store_id'] = $this->userInfo['store_id'];
            $getData['user_id'] = $this->userInfo['id'];
            $getData['status'] = '1';
            $getData['create_time'] = time();
            try{
                Db::startTrans();
                //插入请假数据
                Db::name('qt_work_attendance')->insert($getData);
                //更新用户请假
                Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'7']);
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('添加失败','',204);
            }
            $this->result('添加成功','',200);
        }
        $this->result('无效的请求', '', 204);
    }


    /**
     * 技师加钟
     */
    public function addClock(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['project_id']) || empty($getData['num'])){
                $this->result('缺少参数','',204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('id',$find['order_project_id'])->find();
            $project = Db::name('qt_project')->where('id',$getData['project_id'])->find();
            $add = Db::name('qt_users')->where('id',$getData['engineer_id'])->value('is_add');
            //下新项目
            $insertOrderProject = [
                'store_id'=>$this->userInfo['store_id'],
                'name'=>$project['name'],
                'created_order_id'=>$this->userInfo['id'],
                'order_id'=>$orderProject['order_id'],
                'engineer_id'=>$orderProject['engineer_id'],
                'project_id'=>$getData['project_id'],
                'room_id'=>$orderProject['room_id'],
                'hand_card_id'=>$orderProject['hand_card_id'],
                'old_card_id'=>$orderProject['old_card_id'],
                'order_type'=>'5',
                'num'=>'1',
                'price'=>$project['add_block_price'],
                'status'=>2,
                'is_add'=>$add,
                'start_time'=>time(),
                'end_time'=>$orderProject['end_time'] + ($project['add_block_time'] * 60 ),
                'is_change'=>'1',
                'created_time'=>time(),
            ];
//            try{
                //更新项目订单状态
                Db::name('qt_order_project')->where('id',$orderProject['id'])->update(['end_time'=>$orderProject['end_time'] + ($project['add_block_time'] * 60 ),'status'=>'2']);
                $orderId = Db::name('qt_order_project')->insertGetId($insertOrderProject);
                if($orderProject['hand_card_id'] != ''){
                    //给手牌加金额
                    HandCardM::incHandCardMoney($orderId,$orderProject['hand_card_id'],'1');
                }
                Db::name('qt_order_queue')->where('user_id',$orderProject['engineer_id'])->update(['end_time'=>$orderProject['end_time'] + ($project['add_block_time'] * 60 )]);
                $commission = new Orderproject();
                $commission::commission_order($orderId);
//                Db::commit();
//            }catch(\Exception $e){
//                Db::rollback();
//                $this->result('加钟失败','',204);
//            }
            $this->result('加钟成功','',200);


        }
    }


    /**
     * 更换项目
     */
    public  function  change_project(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            //老项目订单
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id',$getData['order_project_id'])->find();
            if($orderProject['project_id'] == $getData['project_id']){
                $this->result('所换项目与原来一致，请重新选择', '', 204);
            }
            if($orderProject['pay_status'] !='0'){
                $this->result('项目状态有问题，不支持修改', '', 204);
            }
            //新项目
            $newProject = Db::name('qt_project')->where('id',$getData['project_id'])->find();
            $oldProject = Db::name('qt_project')->where('id',$orderProject['project_id'])->find();
            if(!empty($orderProject['start_time'])){
                $startTime = $orderProject['start_time'];
                if($newProject['time'] > $oldProject['time']){
                    $ceil = $newProject['time'] - $oldProject['time'];
                    $endTime = $orderProject['end_time'] + ($ceil*60) ;
                }else{
                    $ceil =$oldProject['time'] -  $newProject['time'];
                    $endTime = $orderProject['end_time'] - ($ceil*60) ;
                }
            }else{
                $startTime = null;
                $endTime = null;
            }
            //新订单信息
            $newOrderProjectInsert = [
                'store_id'=>$orderProject['store_id'],
                'name'=>$newProject['name'],
                'old_name'=>$oldProject['name'],
                'created_order_id'=>$orderProject['created_order_id'],
                'order_id'=>$orderProject['order_id'],
                'engineer_id'=>$getData['engineer_id'],
                'project_id'=>$getData['project_id'],
                'room_id'=>$orderProject['room_id'],
                'hand_card_id'=>$orderProject['hand_card_id'],
                'order_type'=>$orderProject['order_type'],
                'num'=>$orderProject['num'],
                'price'=>$newProject['price'],
                'status'=>$orderProject['status'],
                'is_add'=>'1',
                'is_change'=>'1',
                'created_time'=>time(),
                'sale_id'=>$this->userInfo['id'],
                'start_time'=>$startTime,
                'end_time'=>$endTime,
            ];
            //插入新项目
            $newProjectId =  Db::name('qt_order_project')->insertGetId($newOrderProjectInsert);
            //更新老项目数据
            Db::name('qt_order_project')->where(['id'=>$getData['order_project_id']])->update(['status'=>'5','is_change'=>'3']);
            if($startTime == null){
                $workStatus = '5';
                $queueStatus = '2';
            }else{
                $workStatus = '4';
                $queueStatus = '3';
            }
            Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->update([
                    'old_name'=>$orderProject['name'],
                    'start_time'=>$startTime,
                    'status'=>$queueStatus,
                    'end_time'=>$endTime,
                    'room_id'=>$orderProject['room_id'],
                    'order_project_id'=>$newProjectId
                ]);
            Db::name('qt_users')->where(['id'=>$orderProject['engineer_id']])->update(['work_status'=>$workStatus]);
            //新增新的项目段位费
            Duanwei::DuanweiPrice($getData['engineer_id'],$getData['project_id'],$orderProject['room_id']);
            //删除之前的提成并插入新的接待提成和技师提成
            Db::startTrans();
            try{
                //如果有手牌先减去老项目金额，再加新的金额
                if($orderProject['hand_card_id'] != ''){
                    $handGrant = Db::name('qt_hand_grant')
                        ->where(['hand_card_id'=>$orderProject['hand_card_id'],'status'=>'2'])
                        ->order('id desc')
                        ->find();
                    if(!empty($handGrant)){
                        Db::name('qt_hand_grant')->where(['id'=>$handGrant['id']])->setDec('money',$orderProject['price']);
                        Db::name('qt_hand_grant')->where(['id'=>$handGrant['id']])->setInc('money',$newProject['price']);
                    }else{
                        $this->result('手牌状态不正确，无法换项', '', 204);
                    }
                }
                //插入新的提成
                $project = Db::name('qt_project')->where('id',$getData['project_id'])->find();
                //普通提成
                $commission = new OrdinaryService();
                $commission = $commission->showCommission('1','1',$project);
                //计算接待提成
                $receiver = new ReceiverService();
                $receiver = $receiver->showCommission('1', '1', $project);
                //1=按下单人项目不管技师做什么项目，2=按技师上钟项目不管下单人下什么项目，3=下单人下单项目和技师上钟项目必须相同才有提成
                if($this->storeInfo['receiver_order_commission_type'] == '2'){
                    //更新提成 1 下单人 2 开房人
                    if($this->storeInfo['floor_commission_type'] == '1'){
                        $cashierId =  $orderProject['created_order_id'];
                    }else{
                        $cashierId =  $orderProject['creater_room'];
                    }
                    $update = [
                        'user_id'=>$getData['engineer_id'],
                        'cashier_id'=>$cashierId,
                        'commission' => $commission,//技师提成
                        'receiver' => $receiver,//接待提成
                        'product_id' => $orderProject['project_id'],
                        'order_project_id' => $newProjectId,
                    ];
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$orderProject['id']])->update($update);
                }else if($this->storeInfo['receiver_order_commission_type'] == '1' || $this->storeInfo['receiver_order_commission_type'] == '3'){
                    $update = [
                        'user_id'=>$getData['engineer_id'],
                        'commission' => $commission,//技师提成
                        'product_id' => $orderProject['project_id'],//更新项目ID
                        'order_project_id' => $newProjectId,//更新新订单号
                    ];
                    Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$orderProject['id']])->update($update);
                }
                //更新项目订单表提成
                Db::name('qt_order_project')->where(['id'=>$newProjectId])->update(['commission'=>$commission,'receiver'=>$receiver]);
                //安排等位
                $waitRes = Db::name('qt_wait')
                    ->where(['store_id' => $orderProject['store_id'], 'status' => '1','delay_time'=>'0'])
                    ->where('room_id', 'neq', $orderProject['room_id'])
                    ->order('is_first desc id desc')
                    ->select();
                if (!empty($waitRes)) {
                    $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id', $waitRes[0]['order_id'])->select();
                    $model = new Order();
                    $model->calculation($waitRes[0]['room_id'], $waitRes[0]['project_id'], $waitRes[0]['sex'], '1', $orderProject);
                    Db::name('qt_wait')->where(['id' => $waitRes[0]['id']])->update(['status' => '2']);
                }
                //有段位费的退段位费
                $duanweiData = Db::name('qt_duanwei')
                    ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                    ->where(['project_id'=>$orderProject['project_id']])
                    ->find();
                if(!empty($duanweiData)){
                    //查找技师是否下了商品订单
                    $orderGoodsItem = Db::name('qt_product_order_item')
                        ->where(['goods_id'=>$duanweiData['product_id'],'room_id'=>$orderProject['room_id'],'sale_id'=>$getData['engineer_id']])
                        ->find();
                    if(!empty($orderGoodsItem)){
                        \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                    }
                }
                //如果有手牌先减去老项目金额，再加新的金额
                if ($orderProject['hand_card_id'] != '') {
                    $handGrant = Db::name('qt_hand_grant')
                        ->where(['hand_card_id' => $orderProject['hand_card_id'], 'status' => '2'])
                        ->order('id desc')
                        ->find();
                    if (!empty($handGrant)) {
                        Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setDec('money', $orderProject['price']);
                        Db::name('qt_hand_grant')->where(['id' => $handGrant['id']])->setInc('money', $newProject['price']);
                    } else {
                        $this->result('手牌状态不正确，无法换项', '', 204);
                    }
                }
                Db::commit();
            }catch (Exception $exception){
                Db::rollback();
                $this->result('操作失败'.$exception->getFile().$exception->getLine().$exception->getMessage(),'',204);
            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 催技师
     */
    public function urgeEngineer(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id']) || empty($getData['type'])){
                $this->result('缺少参数', '', 204);
            }
            $find = Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->find();
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where('id',$find['order_project_id'])->find();
            if($getData['type'] == '1'){
                $content = $orderProject['name'].'在'.date('Y-m-d H:i:s').'预计结束'.'现在已经超时,请及时下钟';
            }else{
                $content = '您的订单'.$orderProject['name'].'在'.date('Y-m-d H:i:s',$orderProject['created_time']).'已经下单，请及时上钟';
            }
            $insert = [
                'user_id'=>$this->userInfo['id'],
                'to_user_id'=>$getData['engineer_id'],
                'title'=>'您有一条催钟提醒！',
                'room_id'=>$orderProject['room_id'],
                'order_id'=>$orderProject['id'],
                'content'=>$content,
                'status'=>'1',
                'read'=>'0',
                'type'=>'1',
                'created_time'=>time(),
            ];
            $save = Db::name('qt_message')->insert($insert);
            if($save){
                $this->result('操作成功', '', 200);
            }
            $this->result('系统繁忙，请稍后再试！', '', 204);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 退技师
     */
    public function retreatEngineer(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['engineer_id']) || empty($getData['order_project_id'])){
                $this->result('缺少参数', '', 204);
            }
            $storeInfo = Db::name('qt_store')->where('id',$this->userInfo['store_id'])->find();
            $find = Db::name('qt_order_queue')
                ->where(['user_id'=>$getData['engineer_id']])
                ->find();
            //退技师时间限制
            if($find['start_time'] != null){
                $time = ( time() - $find['start_time'] ) / 60;
                $time = ceil($time);
                if($storeInfo['back_engineer_block'] != '0'){
                    if($time > $storeInfo['back_engineer_block']){
                        $this->result('上钟超过设置时间，无法退技师', '', 204);
                    }
                }
            }
            //退技师支付状态限制
            $orderProject = Db::name('qt_order_project')->where('is_delete',2)->where(['id'=>$getData['order_project_id']])->find();
            if($orderProject['pay_status'] == '1'){
                $this->result('该项目已经支付，无法退技师', '', 204);
            }
            if($orderProject['order_type'] == '1'){
                //判断房间是否有加钟
                $rowData = Db::name('qt_order_project')
                    ->where(['is_delete'=>2,'pay_status'=>'0','room_id'=>$orderProject['room_id'],'engineer_id'=>$getData['engineer_id'],'is_change'=>'1','order_type'=>'5'])
                    ->find();
                if(!empty($rowData)){
                    $this->result('该技师有加钟，请先删除加钟项目', '', 204);
                }
            }
            //退提成
            Db::name('qt_commission_log')->where(['type'=>'1','order_project_id'=>$orderProject['id']])->delete();
            $duanweiData = Db::name('qt_duanwei')
                ->where("FIND_IN_SET(" . $getData['engineer_id'] . ",engineer_id)")
                ->where(['project_id'=>$orderProject['project_id']])
                ->find();
            if(!empty($duanweiData)){
                //查找技师是否下了商品订单
                $orderGoodsItem = Db::name('qt_product_order_item')
                    ->where(['goods_id'=>$duanweiData['product_id'],'room_id'=>$find['room_id'],'business_type'=>'5','pay_status'=>'0'])
                    ->find();
                if(!empty($orderGoodsItem)){
                    \app\common\model\Duanwei::delDuanweiPrice($orderGoodsItem['id']);
                }
            }
//            try{
//                Db::startTrans();
                //恢复技师原来位置
                if(empty($find['old_sort'])){
                    $update['sort'] =$find['sort'];
                }else{
                    $update['sort'] = $find['old_sort'];
                }
                //退手牌总金额
                HandCardM::decHandCardMoney($orderProject['id'],$orderProject['hand_card_id'],'1');
                //如果是加钟的，更新技师时间
                if($orderProject['order_type'] == '5'){
                    $project = Db::name('qt_project')->where(['id'=>$orderProject['project_id']])->find();
                    //查找头钟
                    $titleOrder = Db::name('qt_order_project')
                        ->where(['engineer_id'=>$getData['engineer_id'],'is_delete'=>'2'])
                        ->whereIn('status',['1','2','3'])
                        ->find();
                    //更新头钟下钟时间
                    $time = $orderProject['end_time'] - ($project['add_block_time'] * 60);
                    Db::name('qt_order_project')->where(['id'=>$titleOrder['id']])->update(['end_time'=>$time]);
                    //更新技师排位数据
                    Db::name('qt_order_queue')->where(['user_id'=>$getData['engineer_id']])->update(['end_time'=>$time]);
                    //更新加钟订单状态
                    Db::name('qt_order_project')
                        ->where('is_delete',2)
                        ->where(['id'=>$getData['order_project_id']])
                        ->update(['is_change'=>'2', 'status'=>'4','return_time'=>time()]);
                }else{
                    $update['room_id'] = null;
                    $update['project_id'] = null;
                    $update['order_project_id'] = null;
                    $update['start_time'] = null;
                    $update['end_time'] = null;
                    $update['real_time'] = null;
                    $update['order_user_id'] = null;
                    Db::name('qt_order_queue')->where(['user_id'=>$getData['engineer_id']])->update($update);
                    //更新订单状态
                    Db::name('qt_order_project')
                        ->where('is_delete',2)
                        ->where(['id'=>$getData['order_project_id'],'engineer_id'=>$getData['engineer_id']])
                        ->update(['is_change'=>'2', 'status'=>'4','return_time'=>time()]);
                    //更新房间状态
                    $roomQueue = Db::name('qt_order_queue')
                        ->where(['room_id'=>$find['room_id']])
                        ->where('user_id','neq',$getData['engineer_id'])
                        ->find();
                    //如果没有其他技师更新房间状态
                    if(empty($roomQueue)){
                        Db::name('qt_room')->where('id',$find['room_id'])->update(['status_id'=>'10','retreat_time'=>time()]);
                    }else{
                        Db::name('qt_room')->where('id',$find['room_id'])->update(['status_id'=>$roomQueue['status']]);

                    }
                    //更新技师状态
                    Db::name('qt_users')->where('id',$getData['engineer_id'])->update(['work_status'=>'1']);
                }
                //安排等位
                $waitRes = Db::name('qt_wait')
                    ->where(['store_id' => $this->storeInfo['id'], 'status' => '1', 'delay_time' => '0'])
                    ->where('room_id', 'neq', $find['room_id'])
                    ->order('is_first desc id desc')
                    ->find();
                if (!empty($waitRes)) {
                    if($this->storeInfo['floor_commission_type'] == '1'){
                        //下单人
                        $userID = $orderProject['sale_id'];
                    }else{
                        $userID = $orderProject['creater_room'];
                    }
                    $userInfo = Db::name('qt_users')->where(['id'=>$userID])->find();
                    //查找可以安排的技师
                    $data['man_num'] = 0;
                    $data['woman_num'] = 0;
                    $data['other_num'] = 0;
                    if ($waitRes['sex'] == '1') {
                        $data['man_num'] = $waitRes['number'];
                    }
                    if ($waitRes['sex'] == '2') {
                        $data['woman_num'] = $waitRes['number'];
                    }
                    if ($waitRes['sex'] == '3') {
                        $data['other_num'] = $waitRes['number'];
                    }
                    $data['project_id'] = $waitRes['project_id'];
                    $data['room_id'] = $waitRes['room_id'];
                    $data['hand_card_id'] = '';
                    $data['delay'] = 0;
                    $data['time_type'] = 1;
                    $data['order_type'] = 1;
                    $data['create_id'] = $userInfo['id'] ?? '';
                    $data['sale_id'] = $userID;
                    $orderModel = new \app\common\model\Order();
                    $code = $orderModel->create_order($data, $userInfo);
                    if ($code['code'] == '200') {
                        Db::name('qt_wait')->where(['id' => $waitRes['id']])->update(['status' => '2']);
                    }
                }
                Db::commit();
//            }catch (Exception $exception){
//                Db::rollback();
//                $this->result('操作失败','',204);
//            }
            $this->result('操作成功', '', 200);
        } else {
            $this->result('非法请求', '', 204);
        }
    }


    /**
     * 一键上班
     */
    public function all_go_work(){
        if ($this->request->isPost()) {
            $getData = $this->request->post();
            if(empty($getData['type']) || empty($getData['work_type'])){
                $this->result('缺少参数', '', 204);
            }
            if($getData['type'] == '1'){
                //上班
                $workStatus = '1';
                $isAdd = '1';
            }elseif ($getData['type'] == '2'){
                //下班
                $workStatus = '2';
                $isAdd = '2';
            }
            $userRes = Db::name('qt_users')
                ->where(['store_id'=>$this->userInfo['store_id'],'role'=>'3','work_type'=>$getData['work_type']])
                ->where('work_status','<','3')
                ->column('id');
            foreach ($userRes as $key=>$value){
                Db::name('qt_users')->where('id',$value)->update(['work_status'=>$workStatus,'is_add'=>$isAdd]);
            }
            $this->result('一键上下班成功', '', 200);
        }
    }


}
